// 登录
import { userLogin, permissions, userLogout, userInfo, btnPermissions, getUserMenu } from '@/api/user'
import constant from '@/common/constant/httpStatus'
import store from '@/store'

const state = {
  token: null,
  userInfo: {},
  permissions: [],
  btnPermissions: [],
  menu: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_BTN_PERMISSIONS: (state, btnPermissions) => {
    state.btnPermissions = btnPermissions
  },
  SIGN_OUT: (state) => {
    state.token = null
    state.userInfo = {}
    state.permissions = []
    state.btnPermissions = []
    state.menu = []
    store.state.system.pageTabs = []
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  }
}

const actions = {
  async getMenu ({ commit }, userInfo) {
    try {
      const { data, code } = await getUserMenu()
      if (constant.SUCCESS === code) {
        commit('SET_MENU', data)
        return data
      }
      return []
    } catch (e) {
      return []
    }
  },
  async login ({ commit }, userInfo) {
    try {
      commit('SIGN_OUT')
      const { data, code } = await userLogin(userInfo)
      if (constant.SUCCESS === code) {
        commit('SET_TOKEN', data)
        return code
      }
      return null
    } catch (e) {
      return null
    }
  },

  async logout ({ commit }) {
    try {
      await userLogout()
      commit('SIGN_OUT')
    } catch (e) {
    }
  },

  async getInfo ({ commit }) {
    try {
      const { data, code } = await userInfo()
      if (constant.SUCCESS === code) {
        commit('SET_USER_INFO', data)
      }
    } catch (e) {
    }
  },
  async getPermission ({ commit }) {
    try {
      const { code, data } = await permissions()
      if (constant.SUCCESS === code) {
        commit('SET_PERMISSIONS', data)
        return data
      }
      return []
    } catch (e) {
      return []
    }
  },
  async getBtnPermission ({ commit }) {
    try {
      const { data, code } = await btnPermissions()
      if (constant.SUCCESS === code) {
        commit('SET_BTN_PERMISSIONS', data)
        return data
      }
      return []
    } catch (e) {
      return []
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
// 登录：当用户填写完账号和密码后向服务端验证是否正确，验证通过之后，服务端会返回一个token，拿到token之后（我会将这个token存贮到cookie中，保证刷新页面后能记住用户登录状态），前端会根据token再去拉取一个 user_info 的接口来获取用户的详细信息（如用户权限，用户名等等信息）。
// 权限验证：通过token获取用户对应的 role，动态根据用户的 role 算出其对应有权限的路由，通过 router.addRoutes 动态挂载这些路由。
